#include <fcntl.h>
#include "TcpServer.h"

bool TcpServer::Start(const char * ip, unsigned short port)
{
	m_handle = socket(AF_INET, SOCK_STREAM, 0);
	if (!(m_handle >= 0))
	{
		return false;
	}

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(ip);
	int r = net::setReuseAddr(m_handle);
	fatalif(r, "set socket reuse option failed");
	r = net::setReusePort(m_handle);
	fatalif(r, "set socket reuse port option failed");	
	net::setNonBlock(m_handle);
	util::addFdFlag(m_handle, FD_CLOEXEC);
	if (::bind(m_handle, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
		return false;
	}

	if (listen(m_handle, 10) < 0)
	{
		return false;
	}	
	return true;
}



void TcpServer::HandleRead()
{
	struct sockaddr addr;
	socklen_t addrlen = sizeof(addr);
	reactor::handle_t handle = accept(m_handle, &addr, &addrlen);
	if (!(handle > 0))
	{
		error("socekt error ret %d\n", errno);
	}
	else
	{
		std::shared_ptr<EventHandler> handler =_onClientcb(handle);				
		printf("accpet clent fd %d\n", handle);
		if (g_reactor.RegisterHandler(handler, reactor::kReadEvent) != 0)
		{			
			error("register handler %d failed\n", handler->GetHandle());
		}		
	}
}


